#! /bin/bash
# desc:  use this script to clear the old logs
usage() 
{
    echo "-------------------------------"
    echo "usage:"
    echo "rmlogs.sh -n day -h hour -d logdir"
    echo "  -n day      how old day the logs should to be remove (>0)" 
    echo "  -h hour     how old hour the logs should to be remove (>0)" 
    echo "  -d logdir   the log dir"
    echo "-------------------------------"
    exit 1
}

OLDDAY=""
OLDHOUR=""
LOGDIR=""

while [ $# -gt 0 ]; 
do
    ARG=$1
    shift
    case $ARG in
        -n )
            OLDDAY=$1
            shift;;
        -h )
            OLDHOUR=$1
            shift;;
        -d )
            LOGDIR=$1
            shift;;
        * ) 
            usage
    esac
done

#echo "OLDDAY ${OLDDAY} OLDHOUR ${OLDHOUR} DIR ${LOGDIR}"  >> ~/run.txt 
echo "OLDDAY ${OLDDAY} OLDHOUR ${OLDHOUR} DIR ${LOGDIR}"

if [ ! -d "$LOGDIR" ];then
    echo "the log dir is not exist"
    usage
fi

if [ -n "$OLDDAY" -a -n "$OLDHOUR" ]; then
    echo "the -n and -h is exclusive!"
    usage
fi

if [ -z "$OLDDAY" -a -z "$OLDHOUR" ]; then
    echo "the -n or -h must specify one!"
    usage
fi


# all the log dirs 
PV_DIR=${LOGDIR%/}/pv
SERVER_DIR=${LOGDIR%/}/server
CLICK_DIR=${LOGDIR%/}/click

clear_day()
{
    # first calc the old day 
    PATH_DATE=$(date -d "${OLDDAY} days ago" +"%Y/%m/%d/")
    for DIR in $PV_DIR $SERVER_DIR $CLICK_DIR 
    do
        DEST_DIR=${DIR}/${PATH_DATE}
        echo -e "clear day rm dir: $DEST_DIR"
        rm -rf ${DEST_DIR} 2> /dev/null
    done
}

clear_hour()
{
    # first calc the old hour 
    PATH_HOUR=$(date -d "${OLDHOUR} hours ago" +"%Y/%m/%d/%H")
    for DIR in $PV_DIR $SERVER_DIR $CLICK_DIR 
    do
        DEST_DIR=${DIR}/${PATH_HOUR}
        echo -e "clear hour rm dir: $DEST_DIR"
        rm -rf ${DEST_DIR} 2> /dev/null
    done
    
}

if [ -n "$OLDDAY" ] &&  [ $OLDDAY -ne 0 ]; then
    clear_day
elif [ -n "$OLDHOUR" ] && [ $OLDHOUR -ne 0 ]; then
    clear_hour
fi
